package com.sales.controller;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import com.sales.client.StaffSalesClient;
import com.sales.service.SalesOrderService;
import com.sales.service.SalesProductService;
import com.sales.util.UniqueOrderCode;
import org.comple.erp.pojo.sales.Quotation;
import org.comple.erp.pojo.sales.QuotationDet;
import org.comple.erp.pojo.sales.SalesOrder;
import org.comple.erp.pojo.sales.SalesProduct;
import org.comple.erp.utils.AjaxResult;
import org.comple.erp.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Component
@RestController
public class SalesOrderController {
    @Autowired
    private SalesOrderService salesOrderService;
    @Autowired
    private SalesProductService salesProductService;
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private UniqueOrderCode uniqueOrderCode;
    @Autowired
    private StaffSalesClient staffSalesClient;

    @RequestMapping("/salesOrderList")
    public AjaxResult salesOrderList(@RequestParam Map<String, Object> params, HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        String companyCode = JwtUtil.getCompanyCode(token);
        String userId = JwtUtil.getUserId(token);
        params.put("companyCode", companyCode);
        Map<String, Object> staff = (Map<String, Object>) staffSalesClient.selectById(userId).get("staff");
        List<String> list = (List<String>) staff.get("roleIds");
        for (String roleId : list) {
            if (roleId.equals("2")) {
                params.put("workNumber", staff.get("id"));
            }
        }
        PageInfo<SalesOrder> salesOrderList = salesOrderService.salesOrderList(params);
        return AjaxResult.back("200", "查询成功").add("salesOrderList", salesOrderList);
    }


    @PostMapping("/salesOrderAdd") // 建议明确使用 @PostMapping
    public synchronized AjaxResult quotationAdd(@RequestBody Map<String, Object> params, HttpServletRequest request) throws InterruptedException {

        String token = request.getHeader("Authorization");
        String companyCode = JwtUtil.getCompanyCode(token);
        String userId = JwtUtil.getUserId(token);

        // 提取并转换主表数据
        Map<String, Object> salesOrderMap = (Map<String, Object>) params.get("salesOrder");
        List<Map<String, Object>> salesProductMapList = (List<Map<String, Object>>) params.get("salesProductList");

        if (salesOrderMap == null || salesProductMapList == null) {
            return AjaxResult.back("500", "参数错误");
        }

        // 转换为主表对象
        SalesOrder salesOrder = objectMapper.convertValue(salesOrderMap, SalesOrder.class);
        salesOrder.setId(UUID.randomUUID().toString());
        salesOrder.setWorkNumber(userId);
        salesOrder.setCompanyCode(companyCode);
        String salesOrderCode = "XSDD" + uniqueOrderCode.getCode("cd001", "SALESORDER");
        salesOrder.setCode(salesOrderCode);
//        uniqueOrderCode.getCode(quotation.getCompany_code(), "QUOTATION");


        // 转换为明细列表
        List<SalesProduct> salesProductList = salesProductMapList.stream()
                .map(map -> objectMapper.convertValue(map, SalesProduct.class))
                .collect(Collectors.toList());

        // 保存数据
        Boolean flag = salesOrderService.insertSelective(salesOrder);
        if (!flag) {
            return AjaxResult.back("500", "报价单添加失败");
        }

        // 保存明细数据
        for (SalesProduct salesProduct : salesProductList) {
            salesProduct.setId(UUID.randomUUID().toString());
            salesProduct.setSalesOrder_code(salesOrder.getCode());
            if (!salesProductService.insertSelective(salesProduct)) {
                return AjaxResult.back("500", "报价单详情添加失败");
            }
        }

        return AjaxResult.back("200", "添加成功").add("salesOrderCode", salesOrderCode).add("id", salesOrder.getId());

    }

    @RequestMapping("/selectSalesOrder")
    public AjaxResult selectSalesOrder(@RequestParam String id) {
        SalesOrder salesOrder = salesOrderService.selectByPrimaryKey(id);
        List<SalesProduct> salesProductList = salesProductService.selectBySalesProductCode(salesOrder.getCode());
        if (salesOrder != null && salesProductList != null) {
            return AjaxResult.back("200", "查询成功").add("salesOrder", salesOrder).add("salesProductList", salesProductList);
        }
        return AjaxResult.back("500", "查询失败");
    }


    @RequestMapping("/updateSalesOrder")
    public synchronized AjaxResult updateQuotation(@RequestBody Map<String, Object> request) {
        // 提取并转换主表数据
        Map<String, Object> salesOrderMap = (Map<String, Object>) request.get("salesOrder");
        List<Map<String, Object>> salesProductMapList = (List<Map<String, Object>>) request.get("salesProductList");

        if (salesOrderMap == null || salesProductMapList == null) {
            return AjaxResult.back("500", "参数错误");
        }

        // 转换为主表对象
        SalesOrder salesOrder = objectMapper.convertValue(salesOrderMap, SalesOrder.class);

        // 转换为明细列表
        List<SalesProduct> salesProductList = salesProductMapList.stream()
                .map(map -> objectMapper.convertValue(map, SalesProduct.class))
                .collect(Collectors.toList());

        // 保存数据
        Boolean flag = salesOrderService.updateSalesOrder(salesOrder);
        if (!flag) {
            return AjaxResult.back("500", "报价单修改失败");
        }

        if (salesProductList != null && salesProductList.size() > 0) {
            salesProductService.deleteByCode(salesOrder.getCode());
        }


        // 保存明细数据
        for (SalesProduct salesProduct : salesProductList) {
            salesProduct.setSalesOrder_code(salesOrder.getCode());
            salesProduct.setId(UUID.randomUUID().toString());
            Boolean flag1 = salesProductService.insertSelective(salesProduct);
            if (!flag1) {
                return AjaxResult.back("500", "报价单详情修改失败");
            }
        }

        return AjaxResult.back("200", "修改成功");
    }


    @RequestMapping("deleteSalesOrder")
    public AjaxResult deleteSalesOrder(@RequestBody List<String> id) {
        for (String c : id) {
            Boolean flag = salesOrderService.deleteByPrimaryKey(c);
            if (!flag) {
                return AjaxResult.back("500", "删除失败");
            }
        }
        return AjaxResult.back("200", "删除成功");
    }
}
